﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;

namespace PMBF.Web.Image.Common
{
    public class ImageService
    {
        /// <summary>
        /// 动态选择图片路径
        /// </summary>
        /// <param name="id"></param>
        /// <param name="imgName"></param>
        /// <returns></returns>
        public static string ChoosePath(string id, string imgName)
        {
            //新规则路径,优先查找新规则路径

            string newRulePath = Path.Combine(Config.SaveBasePath, CreateDirPath(id));
            string newRuleImgPath = Path.Combine(newRulePath, imgName);
            if (File.Exists(newRuleImgPath))
            {
                return newRuleImgPath;
            }

            //历史路径
            string oldImgPath = Path.Combine(Config.SaveBasePath, imgName);
            if (File.Exists(oldImgPath))
            {
                string tmp_dir = Path.GetDirectoryName(newRuleImgPath);
                if (!string.IsNullOrEmpty(tmp_dir) && !Directory.Exists(tmp_dir))
                {
                    Directory.CreateDirectory(tmp_dir);
                }
                File.Move(oldImgPath, newRuleImgPath);
                return newRuleImgPath;
            }


            return newRuleImgPath;
        }

        /// <summary>
        /// 根据配置文件夹深度生成路径，完善年份根目录规则
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string CreateDirPath(string name)
        {
            int sub_len = name.Length / Config.SaveDeep;
            List<string> dirList = new List<string>(Config.SaveDeep);
            for (int i = 0; i < Config.SaveDeep; i++)
            {
                int tmp = GetHashCode(name.Substring(i * sub_len, sub_len));
                if (tmp > Config.NumPerDeep)
                {
                    tmp = (tmp % Config.NumPerDeep) + 1;
                }
                dirList.Add(tmp.ToString());
            }
            string path = Path.Combine(dirList.ToArray());
            //追加年份根目录，方便数据转移
            path = Path.Combine(DateTime.Now.Year.ToString(), path);
            return path;
        }

        private static int GetHashCode(string str)
        {
            char[] tmp = str.ToCharArray();
            int res = 0;
            for (int i = 0; i < tmp.Length; i++)
            {
                res += tmp[i];
            }
            return res;
        }
    }
}